# -*-coding:utf-8-*-
"""
@project: SM
@Time: 2024-08-01 19:56
@Author: Loneliness_Burial
@File: db_handler.py
@Motto: 深情不改必坠死海
@software: pycharm
@version: python 3.7
"""

from conf import settings
import os
import json

"""
数据处理层
"""


# 查询数据
def select_data(username, data=True, is_user=True):
    if is_user:
        user_path = os.path.join(
            settings.USER_DATA_DIR, f'{username}.json'
        )
    else:
        user_path = os.path.join(
            settings.GOODS_DATA_DIR, f'{username}.json'
        )
    if not os.path.exists(user_path):
        return
    if not data:
        return True
    with open(user_path, mode='rt', encoding='utf-8-sig') as f:
        user_data = json.load(f)
        return user_data


# 保存数据
def save(user_data):
    username = user_data.get('username')
    user_path = os.path.join(
        settings.USER_DATA_DIR, f'{username}.json'
    )
    with open(user_path, mode='wt', encoding='utf-8') as f:
        json.dump(user_data, f, ensure_ascii=False)
